<script setup>

</script>

<template>
  <div class="app-container">
    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="Plus"
          @click="showSelectProductDialog"
        >选择商品</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          @click="handleBatchDelete"
        >批量删除</el-button>
      </el-col>
    </el-row>

    <!-- 商品列表表格 -->
    <el-table 
      ref="productTable"
      v-loading="loading" 
      :data="selectedProductsList" 
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品名称" align="center" prop="productName" />
      <el-table-column label="SKU编码" align="center" prop="productSn" />
      <el-table-column label="店铺名称" align="center" prop="storeName" />
      <el-table-column label="商品价格" align="center" prop="price" />
      <el-table-column label="库存" align="center" prop="stock" />
      <el-table-column label="结算价格" align="center" prop="originalPrice" />
      <el-table-column label="分类" align="center" width="150">
        <template #default="scope">
          <el-select
            v-model="scope.row.categoryId"
            placeholder="请选择分类"
            clearable
            style="width: 100%;"
            @change="handleCategoryChangeInTable(scope.row)"
          >
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.categoryName"
              :value="item.id"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="活动库存" align="center" width="120">
        <template #default="scope">
          <el-input
            v-model.number="scope.row.activityStock"
            type="number"
            placeholder="请输入"
            min="0"
            style="width: 100%;"
            @change="handleActivityStockChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="兑换积分" align="center" width="120">
        <template #default="scope">
          <el-input
            v-model.number="scope.row.exchangePoints"
            type="number"
            placeholder="请输入"
            min="0"
            style="width: 100%;"
            @change="handleExchangePointsChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 活动时间和提交区域 -->
    <el-row :gutter="10" class="mt8">
      <el-col :span="24">
        <el-form :model="form" label-width="120px">
          <el-form-item label="活动时间" required>
            <el-date-picker
              v-model="form.activityTime"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 400px;"
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="goBack">返回</el-button>
            <el-button type="primary" @click="handleSubmit">提交</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <!-- 选择商品弹框 -->
    <el-dialog
      v-model="selectProductDialogVisible"
      title="选择商品"
      width="80%"
      :before-close="handleCloseDialog"
    >
      <!-- 弹框主内容区域 -->
      <div class="dialog-main">
        <!-- 搜索区域 -->
        <div class="search-area">
          <el-form :model="searchParams" :inline="true" label-width="68px">
            <el-form-item label="商品名称" prop="productName">
              <el-input
                v-model="searchParams.productName"
                placeholder="请输入商品名称"
                clearable
                style="width: 200px;"
                @keyup.enter="handleSearch"
              />
            </el-form-item>
            <el-form-item label="商品分类" prop="categoryId">
              <el-select
                v-model="searchParams.categoryId"
                placeholder="请选择商品分类"
                clearable
                style="width: 300px;"
                @change="handleCategoryChange"
              >
                <el-option
                  v-for="item in categoryOptions"
                  :key="item.id"
                  :label="item.categoryName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
              <el-button icon="Refresh" @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 商品网格区域 -->
        <div class="product-grid">
          <div 
            class="product-item" 
            v-for="item in productList" 
            :key="item.id"
            :class="{ 'selected': selectedProducts.find(p => p.id === item.id) }"
            @click="handleSelectProduct(item)"
          >
            <div class="product-image">
              <img :src="item.mainImage || '/placeholder.png'" alt="商品图片" />
            </div>
            <div class="product-info">
              <div class="product-name">{{ item.productName }}</div>
              <div class="product-unit">{{ item.productParams?.unit || '个' }} {{ item.salesModel || '零售型' }}</div>
              <div class="product-price">¥{{ item.originalPrice }}</div>
            </div>
          </div>
        </div>

        <!-- 分页区域 -->
        <div class="pagination-area">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[12, 24, 36, 48]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!-- 弹框底部按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseDialog">取消</el-button>
          <el-button type="primary" @click="handleConfirmSelect">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AddProduct">
import { listPlatform } from "@/api/shangpin/platform"
import { listClassify } from "@/api/shangpin/classify"
import { addProducts } from "@/api/promotion/products"
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { useRouter } from 'vue-router'

const { proxy } = getCurrentInstance()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const selectedProductsList = ref([])
const selectProductDialogVisible = ref(false)
const productList = ref([])
const categoryOptions = ref([])
const selectedTableRows = ref([]) // 新增：存储表格中选中的行

// 表单数据
const form = reactive({
  activityTime: []
})

// 搜索参数
const searchParams = reactive({
  productName: '',
  categoryId: null
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 12,
  total: 0
})

// 选中的商品
const selectedProducts = ref([])

// 显示选择商品弹框
function showSelectProductDialog() {
  selectProductDialogVisible.value = true
  getCategoryOptions()
  getProductList()
}

// 关闭弹框
function handleCloseDialog() {
  selectProductDialogVisible.value = false
  selectedProducts.value = []
}

// 获取商品分类选项
function getCategoryOptions() {
  listClassify({
    pageNum: 1,
    pageSize: 1000,
    status: 'enabled'
  }).then(response => {
    console.log('分类数据:', response)
    categoryOptions.value = response.rows || []
  }).catch(error => {
    console.error('获取商品分类失败:', error)
    proxy.$modal.msgError("获取商品分类失败：" + (error.message || '未知错误'))
    categoryOptions.value = []
  })
}

// 搜索商品
function handleSearch() {
  console.log('执行搜索，条件:', searchParams)
  pagination.currentPage = 1
  getProductList()
}

// 重置搜索
function resetSearch() {
  searchParams.productName = ''
  searchParams.categoryId = null
  pagination.currentPage = 1
  console.log('重置搜索条件')
  getProductList()
}

// 获取商品列表
function getProductList() {
  loading.value = true
  const params = {
    pageNum: pagination.currentPage,
    pageSize: pagination.pageSize
  }
  
  // 添加搜索条件
  if (searchParams.productName && searchParams.productName.trim()) {
    params.productName = searchParams.productName.trim()
  }
  
  if (searchParams.categoryId) {
    params.categoryId = searchParams.categoryId
  }
  
  console.log('查询参数:', params)
  
  listPlatform(params).then(response => {
    console.log('商品列表响应:', response)
    productList.value = response.rows || []
    pagination.total = response.total || 0
    loading.value = false
  }).catch(error => {
    console.error('获取商品列表失败:', error)
    proxy.$modal.msgError("获取商品列表失败：" + (error.message || '未知错误'))
    productList.value = []
    pagination.total = 0
    loading.value = false
  })
}

// 分页大小改变
function handleSizeChange(size) {
  pagination.pageSize = size
  getProductList()
}

// 当前页改变
function handleCurrentChange(page) {
  pagination.currentPage = page
  getProductList()
}

// 选择商品
function handleSelectProduct(product) {
  const index = selectedProducts.value.findIndex(item => item.id === product.id)
  if (index > -1) {
    selectedProducts.value.splice(index, 1)
  } else {
    selectedProducts.value.push(product)
  }
}

// 确认选择商品
function handleConfirmSelect() {
  if (selectedProducts.value.length === 0) {
    proxy.$modal.msgWarning("请选择商品")
    return
  }
  
  // 将选中的商品添加到selectedProductsList
  selectedProducts.value.forEach(product => {
    const existingIndex = selectedProductsList.value.findIndex(item => item.id === product.id)
    if (existingIndex === -1) {
      selectedProductsList.value.push({
        id: product.id,
        productName: product.productName,
        productSn: product.productSn,
        storeName: product.shopName,
        shopId: product.shopId || 1, // 添加店铺ID
        price: product.originalPrice,
        stock: product.stock,
        originalPrice: product.originalPrice,
        categoryName: product.categoryName,
        categoryId: product.categoryId || null, // 添加分类ID字段
        activityStock: 0,
        exchangePoints: 0,
        salesModel: product.salesModel,
        mainImage: product.mainImage,
        productParams: product.productParams
      })
    }
  })
  
  proxy.$modal.msgSuccess("商品选择成功")
  selectProductDialogVisible.value = false
  selectedProducts.value = []
}

// 批量删除
function handleBatchDelete() {
  if (selectedTableRows.value.length === 0) {
    proxy.$modal.msgWarning("请选择要删除的商品")
    return
  }
  
  const selectedIds = selectedTableRows.value.map(item => item.id)
  const selectedNames = selectedTableRows.value.map(item => item.productName).join('、')
  
  proxy.$modal.confirm(`是否确认删除选中的商品：${selectedNames}？`).then(function() {
    // 从已选商品列表中移除选中的商品
    selectedProductsList.value = selectedProductsList.value.filter(item => !selectedIds.includes(item.id))
    selectedTableRows.value = [] // 清空表格选择
    proxy.$modal.msgSuccess("批量删除成功")
  }).catch(() => {})
}

// 删除单个商品
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除商品名称为"' + row.productName + '"的数据项？').then(function() {
    // 从已选商品列表中移除该商品
    const index = selectedProductsList.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      selectedProductsList.value.splice(index, 1)
      // 同时从表格选择中移除
      selectedTableRows.value = selectedTableRows.value.filter(item => item.id !== row.id)
      proxy.$modal.msgSuccess("删除成功")
    }
  }).catch(() => {})
}

// 选择改变
function handleSelectionChange(selection) {
  // 这里处理表格中已选商品的选择变化
  // selection 是当前表格中选中的商品列表
  selectedTableRows.value = selection
  console.log('表格选择变化:', selection)
}

// 分类选择改变
function handleCategoryChange(value) {
  console.log('分类选择改变，当前值:', value)
  searchParams.categoryId = value
  pagination.currentPage = 1
  getProductList()
}

// 表格中分类选择改变
function handleCategoryChangeInTable(row) {
  console.log('表格中分类选择改变，当前值:', row.categoryId)
  // 根据选择的分类ID更新分类名称
  if (row.categoryId) {
    const selectedCategory = categoryOptions.value.find(item => item.id === row.categoryId)
    if (selectedCategory) {
      row.categoryName = selectedCategory.categoryName
    }
  } else {
    row.categoryName = ''
  }
}

// 活动库存改变
function handleActivityStockChange(row) {
  console.log('活动库存改变，当前值:', row.activityStock)
  // 这里可以进行其他逻辑，例如更新活动库存
}

// 兑换积分改变
function handleExchangePointsChange(row) {
  console.log('兑换积分改变，当前值:', row.exchangePoints)
  // 这里可以进行其他逻辑，例如更新兑换积分
}

// 清空表格选择
function clearTableSelection() {
  if (proxy.$refs.productTable) {
    proxy.$refs.productTable.clearSelection()
  }
  selectedTableRows.value = []
}

// 返回上一页
function goBack() {
  router.go(-1)
}

// 提交表单
function handleSubmit() {
  if (!form.activityTime || form.activityTime.length === 0) {
    proxy.$modal.msgWarning("请选择活动时间")
    return
  }
  
  // 检查是否有选中的商品（基于表格复选框选择）
  if (selectedTableRows.value.length === 0) {
    proxy.$modal.msgWarning("请选择要提交的商品")
    return
  }

  // 验证必填字段（只验证选中的商品）
  const invalidProducts = selectedTableRows.value.filter(product => {
    return !product.categoryId || product.activityStock === undefined || product.activityStock === null || product.exchangePoints === undefined || product.exchangePoints === null
  })

  if (invalidProducts.length > 0) {
    proxy.$modal.msgWarning("请完善商品信息：分类、活动库存、兑换积分为必填项")
    return
  }

  // 验证数值合理性（只验证选中的商品）
  const invalidValues = selectedTableRows.value.filter(product => {
    return product.activityStock < 0 || product.exchangePoints < 0 || 
           product.activityStock > (product.stock || 0)
  })

  if (invalidValues.length > 0) {
    proxy.$modal.msgWarning("请检查数值合理性：活动库存不能为负数且不能超过商品库存，兑换积分不能为负数")
    return
  }

  // 构建提交数据（只提交选中的商品）
  const submitDataList = selectedTableRows.value.map(product => {
    const currentTime = new Date()
    const endTime = new Date(form.activityTime[1])
    
    return {
      productId: product.id,
      shopId: product.shopId || 1, // 如果没有shopId，使用默认值
      categoryId: product.categoryId,
      stockQuantity: product.stock || 0, // 商品库存数量
      activityRemainingStock: product.activityStock || 0, // 活动库存
      exchangePoints: product.exchangePoints || 0, // 兑换积分
      status: endTime < currentTime ? '已关闭' : '已开始', // 根据结束时间判断状态
      activityStartTime: form.activityTime[0], // 活动开始时间
      activityEndTime: form.activityTime[1] // 活动结束时间
    }
  })

  console.log('提交数据:', submitDataList)

  // 调用API保存数据
  proxy.$modal.confirm(`确认提交选中的 ${selectedTableRows.value.length} 个商品到积分商品列表？`).then(function() {
    loading.value = true
    
    // 逐个提交商品
    const promises = submitDataList.map(data => addProducts(data))
    
    Promise.all(promises).then(responses => {
      console.log('API响应:', responses)
      proxy.$modal.msgSuccess("提交成功，商品已添加到积分商品列表")
      loading.value = false
      
      // 提交成功后，从列表中移除已提交的商品
      const submittedIds = selectedTableRows.value.map(item => item.id)
      selectedProductsList.value = selectedProductsList.value.filter(item => !submittedIds.includes(item.id))
      clearTableSelection() // 清空表格选择
      
      // 跳转到积分商品列表页面并强制刷新
      router.replace({
        path: '/promotion/products',
        query: { 
          refresh: 'true'
        }
      })
    }).catch(error => {
      console.error('提交失败:', error)
      proxy.$modal.msgError("提交失败：" + (error.message || '未知错误'))
      loading.value = false
    })
  }).catch(() => {
    // 用户取消提交
  })
}

onMounted(() => {
  // 页面加载时的初始化
  getCategoryOptions()
})
</script>

<style scoped lang="scss">
.dialog-main {
  padding: 20px;
  display: flex;
  flex-direction: column;
  height: 500px;
}

.search-area {
  margin-bottom: 20px;
  
  .el-form {
    margin-bottom: 0;
  }
}

.product-grid {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
  overflow-y: auto;
  margin-bottom: 20px;
}

.product-item {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    border-color: #f56c6c;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
  
  &.selected {
    border-color: #f56c6c;
    background-color: #fef0f0;
  }
  
  .product-image {
    width: 100%;
    height: 120px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f7fa;
    margin-bottom: 10px;
    
    img {
      max-width: 100%;
      max-height: 100%;
      object-fit: cover;
    }
  }
  
  .product-info {
    .product-name {
      font-weight: bold;
      margin-bottom: 5px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    
    .product-unit {
      color: #909399;
      font-size: 12px;
      margin-bottom: 5px;
    }
    
    .product-price {
      color: #f56c6c;
      font-weight: bold;
    }
  }
}

.pagination-area {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}

.mt8 {
  margin-top: 8px;
}

.mb8 {
  margin-bottom: 8px;
}
</style>